package pager;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tikeyc.mobileplayer.R;
import com.tikeyc.mobileplayer.activity.SystemVideoPlayer;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.common.util.LogUtil;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.lang.reflect.Type;
import java.util.ArrayList;

import adapter.VideoNetPagerAdapter;
import base.BasePager;
import common.Constants;
import domain.MediaItem;
import utils.CacheUtils;
import utils.StringUtils;
import view.DropDownListView;


/**
 * Created by public1 on 2017/1/4.
 *
 *
 * 视频json数据接口：http://api.m.mtime.cn/PageSubArea/TrailerList.api
 */

public class VideoNetPager extends BasePager {

    private static final String CACHE_KEY = "video_net_pager_cache_key";

    @ViewInject(R.id.listView)
    private DropDownListView listView;

    @ViewInject(R.id.textView_no_media)
    private TextView textView_no_media;

    @ViewInject(R.id.progressBar)
    private ProgressBar progressBar;

    ArrayList<MediaItem> mediaItems;

    private VideoNetPagerAdapter listAdapter;
    //刷新UI
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            if (mediaItems != null && mediaItems.size() > 0) {
                isInitData = true;
                textView_no_media.setVisibility(View.GONE);

                //
            listAdapter = new VideoNetPagerAdapter(context,mediaItems);
            listView.setAdapter(listAdapter);
            } else {
                isInitData = false;
                textView_no_media.setVisibility(View.VISIBLE);
            }

            //
            progressBar.setVisibility(View.GONE);

        }
    };

    public VideoNetPager(Context context) {
        super(context);

    }

    @Override
    public View initView() {

        View view = View.inflate(context, R.layout.video_net_pager,null);
        x.view().inject(VideoNetPager.this,view);
        listView.setDropDownStyle(true);
        listView.setOnBottomStyle(true);
        listView.setOnDropDownListener(new DropDownListView.OnDropDownListener() {
            @Override
            public void onDropDown() {
                Log.e("TAG","setOnDropDownListener");
                getDataFromNet();
            }
        });

        listView.setOnBottomListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.e("TAG","setOnBottomListener");
                Toast.makeText(context,"无更多",Toast.LENGTH_SHORT).show();
                listView.setOnBottomStyle(false);
            }
        });

//        listView = (ListView) view.findViewById(R.id.listView);
//        textView_no_media = (TextView) view.findViewById(R.id.textView_no_media);
//        progressBar = (ProgressBar) view.findViewById(R.id.progressBar);


        //
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//                MediaItem mediaItem = mediaItems.get(i);
//                Log.e("TAG",mediaItem.toString());

//                //1调用系统所有播放器-隐式意图
//                Intent intent = new Intent();
//                intent.setDataAndType(Uri.parse(mediaItem.getData()),"video/*");
//                context.startActivity(intent);

                //2调用自定义播放器
//                Intent intent = new Intent(context, SystemVideoPlayer.class);
//                intent.setDataAndType(Uri.parse(mediaItem.getData()),"video/*");
//                context.startActivity(intent);

                //3传递列表数据
                Intent intent = new Intent(context, SystemVideoPlayer.class);
//                Intent intent = new Intent(context, VitamioVideoPlayer.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("medioItems",mediaItems);
                intent.putExtras(bundle);
                i = i - 1;//下拉刷新多了一行，需要-1
                intent.putExtra("position",i);
                context.startActivity(intent);

            }
        });
        return view;
    }


    @Override
    public void initData() {
        super.initData();

        loadData();

        Log.e("TAG","网络视频界面");
    }

    private void loadData() {
        String cacheString = CacheUtils.getCacheString(context,CACHE_KEY);
        if (!StringUtils.isEmpty(cacheString)){
            listView.onDropDownComplete();
            listView.onBottomComplete();
            try {
                //先显示缓存
                paramsData(cacheString);
                //在加载最新数据
                getDataFromNet();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            getDataFromNet();
        }
    }

    private void getDataFromNet() {
        final RequestParams params = new RequestParams(Constants.VIDEO_NET_URL);
        x.http().get(params, new Callback.CommonCallback<String >() {

            @Override
            public void onSuccess(String result) {
                LogUtil.e("onSuccess"+result);
//                Log.e("TAG",result);
                //
                CacheUtils.cacheString(context,CACHE_KEY,result);
                try {
                    paramsData(result);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                LogUtil.e("onError"+ex.getMessage());
                //刷新UI
                handler.sendEmptyMessage(0);
            }

            @Override
            public void onCancelled(CancelledException cex) {
                LogUtil.e("onCancelled"+cex.getMessage());
            }

            @Override
            public void onFinished() {
                LogUtil.e("onFinished");
                listView.onDropDownComplete();
                listView.onBottomComplete();
            }
        });
    }

    /**数据解析
     * @param result
     */
    private ArrayList<MediaItem> paramsData(String result) throws JSONException {

        JSONObject jsonObject = new JSONObject(result);
        JSONArray jsonArray = jsonObject.getJSONArray("trailers");
//        String trailers = jsonObject.getString("trailers");

        mediaItems = new ArrayList<MediaItem>();

        if (jsonArray != null && jsonArray.length() > 0) {
            for (int i = 0; i < jsonArray.length();i++){
                JSONObject jsonObjectItem = jsonArray.getJSONObject(i);
                if (jsonObjectItem != null) {
                    String moveName = jsonObjectItem.getString("movieName");
                    String coverImg = jsonObjectItem.getString("coverImg");
                    String summary = jsonObjectItem.getString("summary");
                    String hightUrl = jsonObjectItem.getString("hightUrl");

                    MediaItem mediaItem = new MediaItem();
                    mediaItem.setMovieName(moveName);
                    mediaItem.setCoverImg(coverImg);
                    mediaItem.setSummary(summary);
                    mediaItem.setHightUrl(hightUrl);
                    mediaItems.add(mediaItem);
                }
            }
        }

//        Gson gson = new Gson();
//        Type typeOfT = new TypeToken<ArrayList<MediaNetItem>>(){}.getType();
//        Log.e("TAG","mediaNetItemModel--1");
//        mediaNetItems = gson.fromJson(trailers,typeOfT);
//        Log.e("TAG","mediaNetItemModel--2");
////        mediaNetItemModel = gson.fromJson(result,MediaNetItemModel.class);
////        ArrayList<MediaNetItem> mediaNetItems = mediaNetItemModel.trailers;
//        Log.e("TAG","mediaNetItemModel--3");

        //刷新UI
        handler.sendEmptyMessage(0);

        return mediaItems;
    }

    public class MediaNetItemModel {
        private ArrayList<MediaItem> trailers;

        public ArrayList<MediaItem> getTrailers() {
            return trailers;
        }

        public void setTrailers(ArrayList<MediaItem> trailers) {
            this.trailers = trailers;
        }
    }
}
